<?php


namespace App\logic;


use App\Models\DrugsModel;
use App\servers\RedisService;

class DrugLogic
{
    public static function Index(){
        $redis = RedisService::getInstance()->getRedis();
        $redis->select(5);
        $data = json_decode($redis->get('drug'),true);
        if ($data) return $data;
        $data = DrugsModel::getList();
        $redis->set('drug', json_encode($data,true));
        if (!$data) throw new \Exception('数据出错！');
        return $data;
    }
    public static function Read($id){
        $redis = RedisService::getInstance()->getRedis();
        $redis->select(5);
        $data = json_decode($redis->get('drug'),true);
        $data = $data['data'];
        foreach ($data as $value){
            if ($value['id'] == $id['drug_id']) {return $value;}
        }
    }
    public static function Create($data){
        request()->validate([
            'name'=>'required',
            'common_name'=>'required',
            'specifications'=>'required',
            'dosage_form'=>'required',
            'manufacturer'=>'required',
            'price'=>'required',
            'stock'=>'required'
        ],[
            'name.required'=>'医药名称不得为空',
            'common_name.required'=>'医药通用名称不得为空',
            'specifications.required'=>'医药规格不得为空',
            'dosage_form.required'=>'医药剂型不得为空',
            'manufacturer.required'=>'医药生产厂家不得为空',
            'price.required'=>'医药价格不得为空',
            'stock.required'=>'医药库存不得为空'
        ]);
        $data = DrugsModel::postCreate($data);
        if (!$data) throw new \Exception('添加失败！');
        return $data;
    }
}
